<template>
  <div class="editUpdateStrategy">
    <full-parent-dom-with-dask :loading="spinningLoading"></full-parent-dom-with-dask>
    <a-form-model
      ref="formComp"
      :model="formData"
      :rules="rules"
      layout="horizontal"
      class="AsteriskAfter newEditStyle editUpdateStrategyForm"
    >
      <a-row :gutter="40">
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('policyName')" class="customFormModelItem" prop="name">
            <a-input v-model.trim="formData.name" :disabled="isReadonly" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="40">
        <!-- 条件策略 -->
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('tjcl')" class="customFormModelItem" prop="conditionStrategyId">
            <condition-strategy-select
              :type="2"
              v-model="formData.conditionStrategyId"
              :time="time"
              :version-type="versionType"
              :readonly="isReadonly"
              @changeoption="selectCondition"
            ></condition-strategy-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 选择车辆版本start -->
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('selectVehicleVersion')" class="customFormModelItem"></a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="40">
        <a-col :md="12" :sm="24">
          <a-form-model-item :label="$t('vehicleModel')" prop="modelId">
            <car-model-select
              :disabled="isReadonly"
              :query="{ time: time }"
              :defaultValue="formData.modelId"
              @changeoption="selectCarModel"
              :hasAll="false"
              :clear="true"
              mode="default"
              placeholder="vehicleModel"
            ></car-model-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-model-item :label="$t('smartDrivingDomainVersion')" prop="vehicleVersionId">
            <vehicle-version-select
              mode="default"
              :disabled="isReadonly || !formData.modelId"
              :time="versionSelectTime"
              v-model="formData.vehicleVersionId"
              :query="vehicleVersionSelectQuery"
              :defaultVersionType="upgradeTriggerType"
              @changeoption="selectVehicleVersion"
            ></vehicle-version-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 选择车辆版本end -->
    </a-form-model>
    <div class="editUpdateStrategyVehicleVersionLists">
      <view-ecu-version-config :ecuVersionLists="ecuVersions" :loading="loadingEcuVersions"></view-ecu-version-config>
    </div>
  </div>
</template>
<script>
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import ConditionStrategySelect from '@/views/components/StrategySelect'
import CarModelSelect from '@/views/components/CarModelSelect'
import ViewEcuVersionConfig from '@/views/software/vehicleVersion/components/ViewEcuVersionConfig.vue'
import VehicleVersionSelect from '@/views/components/VehicleVersionSelect'
import { strategyInitFormData } from '../config/form'
import { checkTextLen } from '@/utils/validate'
import lodash from 'lodash'
import { mapState } from 'vuex'
import commonFun from "@/utils/common";

export default {
  components: {
    FullParentDomWithDask,
    ConditionStrategySelect,
    CarModelSelect,
    VehicleVersionSelect,
    ViewEcuVersionConfig
  },
  props: {
    isReadonly: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    },
    time: {
      type: Number,
      default: 78140
    },
    // 对应新的testType
    versionType: {
      type: String,
      default: ''
    },
    //老versionType， PROD/TEST
    upgradeTriggerType: {
      type: String,
      default: 'TEST'
    },
    isCopy: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState({
      strategyUpgradeTypeDictCode: (state) => state.dict.strategyUpgradeTypeDictCode
    }),
    vehicleVersionSelectQuery () {
      return { modelId: this.formData.modelId }
    }
  },
  data () {
    return {
      formData: lodash.cloneDeep(strategyInitFormData),
      spinningLoading: false,
      rules: {
        name: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen() }],
        conditionStrategyId: [{ required: true, message: this.$t('pleaseInput') }],
        modelId: [{ required: true, message: this.$t('pleaseInput') }],
        vehicleVersionId: [{ required: true, message: this.$t('pleaseInput') }]
      },
      versionSelectTime: 0,
      // 当前版本对应的零件版本配置
      ecuVersions: [],
      loadingEcuVersions: false
    }
  },
  watch: {
    time: {
      handler () {
        // this.resetFormData(!this.id || this.isCopy)
        if (this.id) {
          this.getDetailData()
        }
      },
      immediate: true
    },
    'formData.vehicleVersionId': {
      handler (val) {
        this.getEcuVersionsData(val)
      }
    }
  },
  created() {
    this.resetFormData(!this.id || this.isCopy)
  },
  methods: {
    getPopupContainer (node) {
      return node.parentNode.parentNode
    },
    // 获取当前车辆版本的零件配置
    getEcuVersionsData (vehicleVersionId) {
      this.ecuVersions = []
      if (!vehicleVersionId || vehicleVersionId.length === 0 || this.loadingEcuVersions) {
        return
      }
      this.loadingEcuVersions = true
      this.$store
        .dispatch('getVehicleVersionDetailData', { id: vehicleVersionId,versionType:this.upgradeTriggerType, isOnlyEcuVersion: true })
        .then((res) => {
          this.ecuVersions = res
        })
        .finally(() => {
          this.loadingEcuVersions = false
        })
    },
    // 选择车型
    selectCarModel (val) {
      this.formData.modelId = val
      this.formData.vehicleVersionId = undefined
      // this.formData.vehicleVersionId = ''
      this.versionSelectTime = Date.now()
      this.$refs.formComp.validateField('modelId')
    },
    // 选择条件策略
    selectCondition (val) {
      // this.formData.conditionStrategyId = val
      this.$refs.formComp.validateField('conditionStrategyId')
    },
    // 选择车辆版本
    selectVehicleVersion (val, item) {
      item && (this.upgradeTriggerType = item.versionType);
      this.formData.vehicleVersionId = val;
      this.$refs.formComp.validateField('vehicleVersionId')
    },
    // 获取详情数据
    getDetailData () {
      this.spinningLoading = true
      this.$store
        .dispatch('getStrategyDetailData', {id : this.id,versionType:this.versionType})
        .then((res) => {
          const { data } = res
          if (data) {
            this.formData.id = this.isCopy ? '' : this.id
            if (this.formData.id) {
              this.formData.name = data.name
            }
            this.formData.conditionStrategyId = data.conditionStrategyId
            this.formData.type = 1
            this.selectCarModel(data.modelId, data.vehicleVersionId)
            this.getEcuVersionsData(data.vehicleVersionId)
            this.selectVehicleVersion(data.vehicleVersionId)
          }
        })
        .finally(() => {
          this.spinningLoading = false
        })
    },
    resetFormData (isSetName = true) {
      this.$refs.formComp && this.$refs.formComp.resetFields()
      this.formData = lodash.cloneDeep(strategyInitFormData)
      if (isSetName) {
        this.setDefaultName()
      }
    },
    setDefaultName () {
      const name = this.$t('sjcl')
      this.formData.name = `${name}[${this.$commonFun.getDateMinuteStr(new Date())}]`
    },
    // 获取表单中的数据
    getFormData () {
      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate((valid) => {
          if (!valid) {
            reject(valid)
            return
          }
          const formData = { ...this.formData }
          formData.type = 1
          formData.versionType = this.versionType;
          // formData.upgradeTriggerType = this.upgradeTriggerType;
          resolve(formData)
        })
      })
    }
  }
}
</script>
<style scoped lang="less">
.editUpdateStrategy {
  overflow: scroll;
  position: relative;
  display: flex;
  flex-direction: column;
  .editUpdateStrategyForm {
    flex: none;
  }
  .editUpdateStrategyVehicleVersionLists {
    flex: 1 0 0;
    min-height: 220px;
  }
}
</style>
